package com.zeng.configuration.microprofile.config.source;

import org.eclipse.microprofile.config.spi.ConfigSource;

import java.util.Collections;
import java.util.Map;
import java.util.Set;

/**
 * @author zyb
 * @date 2021-03-22 21:25
 */
public abstract class MapBasedConfigSource implements ConfigSource {
    private final String name;
    private final int ordinal;
    private final Map<String, String> source;

    public MapBasedConfigSource(String name, int ordinal) {
        this.name = name;
        this.ordinal = ordinal;
        try {
            source = prepareConfigData();
        } catch (Throwable t) {
            throw new IllegalStateException("准备数据源错误。", t);
        }
    }

    public MapBasedConfigSource(String name, int ordinal, Map<String, String> source) {
        this.name = name;
        this.ordinal = ordinal;
        this.source = source;
    }

    @Override
    public Map<String, String> getProperties() {
        return Collections.unmodifiableMap(source);
    }

    @Override
    public Set<String> getPropertyNames() {
        return source.keySet();
    }

    @Override
    public String getValue(String propertyName) {
        return source.get(propertyName);
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public int getOrdinal() {
        return ordinal;
    }

    /**
     * 准备配置数据
     *
     * @return 返回准备好的数据
     * @throws Throwable throwable
     */
    protected abstract Map<String, String> prepareConfigData() throws Throwable;
}
